package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.siot.adapter.MovilAdapter;
import com.ingenio.siot.adapter.TipoMovilAdapter;
import com.ingenio.siot.entity.Movil;
import com.ingenio.siot.entity.TipoMovil;

/**
 * Servlet implementation class DevolverMovilServlet
 */
@WebServlet("/DevolverMoviles")
public class DevolverMovilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverMovilesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] idsTipoMovil = request.getParameterValues("idsTipoMovil[]");
		if (idsTipoMovil != null){
			MovilAdapter ma = new MovilAdapter();
			TipoMovilAdapter tma = new TipoMovilAdapter();
			List<TipoMovil> tiposMoviles = new ArrayList<TipoMovil>();
			try{
				for(int i=0;i<idsTipoMovil.length;i++){
					tiposMoviles.add(tma.devolverTipoMovil(Integer.parseInt(idsTipoMovil[i])));
				}
				List<Movil> moviles = ma.devolverMovilesdesdeListaTipoMovil(tiposMoviles);
				
				JSONObject json = new JSONObject();
				JSONArray ja = new JSONArray();
				for(Movil m:moviles){
					JSONObject jo = new JSONObject();
					jo.put("idMovil", m.getIdMovil());
					jo.put("idTipo", m.getTipoMovil().getIdTipoMovil());
					jo.put("descripcion", m.getDescMovil());
					jo.put("patente", m.getPatente());
					jo.put("imgTipo", m.getTipoMovil().getUrlIcono());
					ja.put(jo);
				}
				json.put("moviles", ja);
				response.setContentType("application/json");
				response.getWriter().write(json.toString());
			} 
			catch (Exception e) {
				e.printStackTrace();
			}
		}else{
		}
	}

}
